package com.jinbai.servlet.track;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jinbai.util.DBUtil;
import com.jinbai.util.Log;
import jdk.internal.util.xml.impl.Input;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/studio/track/track.om")
public class TrackOMContentServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        final String tid = req.getParameter("tid");
        String type;
        InputStream content;
        try (Connection con = DBUtil.connection()) {
            String sql = "select type, content from tracks where tid = ?";
            try (PreparedStatement ps = con.prepareStatement(sql)) {
                ps.setString(1, tid);
                Log.println("执行SQL：" + ps);
                final ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    type = rs.getString("type");
                    content = rs.getBinaryStream("content");
                } else {
                    throw new RemoteException("该专辑中未绑定任何音源");
                }
            }
        }
        resp.setContentType(type);
        ServletOutputStream outputStream = resp.getOutputStream();
        byte[] buf = new byte[4096];
        while (true) {
            int n = content.read(buf);
            if (n == -1) {
                break;
            }
            outputStream.write(buf, 0, n);
        }
        outputStream.flush();
        content.close();
    }
}
